let __webRoot = "/scripttool";

let __Global = {

    ResultType: {
        success: "0000",
        unauthorized: "401",
        accessDenied: "403",
        serverError: "500"
    },

    getFrameVue: function (frameRef) {
        //return this.$refs[frameRef].contentWindow.app.__vue__;
        return window.app.__vue__.$refs[frameRef].contentWindow.app.__vue__;
    },
    getParentVue: function () {
        return parent.app.__vue__;
    },

    getPageUrl: function (pageUrl, params) {
        let url = __webRoot + "/" + pageUrl;
        if (pageUrl.indexOf("?") != -1) {
            url += "&__t=" + new Date().getTime();
        } else {
            url += "?__t=" + new Date().getTime();
        }
        for (let key in params) {
            url += "&" + key + "=" + params[key];
        }
        return url;
    },

    getServerUrl: function (serverUrl) {
        return __webRoot + serverUrl;
    },

    getParam: function (name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return r[2];
        return null;
    },

    winHeight: function () {
        return window.innerHeight;
    },

    winWidth: function () {
        return window.innerWidth;
    },

    tableHeight: function (toolbarHeight, pageBarHeight) {
        toolbarHeight = toolbarHeight || 48;
        pageBarHeight = pageBarHeight || 48;
        return (window.innerHeight - toolbarHeight - pageBarHeight);
    },
    modalHeight: function (paddingHeight) {
        paddingHeight = paddingHeight || 160;
        return (window.innerHeight - paddingHeight) * 0.99 + "px";
    },
    modalWidth: function (value) {
        return value || "780";
    },

};

function CRUDHelper(_thisApp) {
    let thisApp = _thisApp || window.app.__vue__;
    let params = {};
    let title = "确定删除当前记录吗？";
    let url = "";

    this.setParams = function (_params) {
        params = _params;
        return this;
    };

    this.setTitle = function (_title) {
        title = _title;
        return this;
    };

    this.setUrl = function (_url) {
        url = _url;
        return this;
    };

    this.queryPageTable = function () {
        url = url || thisApp.listUrl;
        new PostMethod(thisApp)
            .setUrl(url)
            .setParams(params)
            .request((resp) => {
                if (resp.code == __Global.ResultType.success && resp.data) {
                    thisApp.dataList = resp.data.content;
                    thisApp.total = resp.data.totalElements;

                }
            });
    };

    this.queryTable = function () {
        url = url || thisApp.listUrl;
        new PostMethod(thisApp)
            .setUrl(url)
            .setParams(params)
            .request((resp) => {
                if (resp.code == __Global.ResultType.success && resp.data) {
                    thisApp.dataList = resp.data;

                }
            });
    };

    this.load = function (callback) {
        url = url || thisApp.loadUrl;
        new PostMethod(thisApp)
            .setUrl(url)
            .setParams(params)
            .request((resp) => {
                if (resp.code == __Global.ResultType.success && resp.data) {
                    thisApp.formData = resp.data;
                    
                    //配置组件权限
                    thisApp.$nextTick(() => {
                        window.setTimeout(() => {
                            if (callback) {
                                callback();
                            }
                        }, 500);
                    });
                }
            });
    };

    this.save = function (callback) {
        url = url || thisApp.saveUrl;
        thisApp.$refs.formData.validate((valid) => {
            if (valid) {
                new PostMethod(thisApp)
                    .setUrl(url)
                    .setParams(params)
                    .request((resp) => {
                        if (resp.code != __Global.ResultType.success) {
                            thisApp.$Message.error(resp.msg);
                        } else {
                            thisApp.$Message.success("保存成功");
                        }
                        //配置组件权限
                        thisApp.$nextTick(() => {
                            window.setTimeout(() => {
                                if (callback) {
                                    callback();
                                }
                            }, 500);
                        });
                        
                    });
            }
        });
    };

    this.delete = function () {
        url = url || thisApp.deleteUrl;
        thisApp.$Modal.confirm({
            title: title,
            onOk: () => {
                // let param = { id: id };
                new PostMethod(thisApp)
                    .setUrl(url)
                    .setParams(params)
                    .request((resp) => {
                        if (resp.code != __Global.ResultType.success) {
                            thisApp.$Message.error(resp.msg);
                        } else {
                            thisApp.$Message.success("操作成功");
                        }
                        thisApp.loadTableData();
                    });
            },
            onCancel: () => {
                //
            }
        });
    };

    return this;
}

class PostMethod {
    constructor(thisApp) {
        this.thisApp = thisApp || window.app.__vue__;
        this.url = "";
        this.data = {};

    }

    setUrl(url) {
        this.url = url;
        return this;
    };

    setParams(jsonParams) {
        this.data = JSON.stringify(jsonParams);
        return this;
    };

    request(callback) {
        let headers = {};
        $.ajax({
            url: this.url,
            type: "post",
            data: this.data,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            headers: headers,
            xhrFields: {
                // 设置为true，避免跨域情况下漏传session
                withCredentials: true
            },
            timeout: 10000,
            success(resp) {
                if (resp.code == __Global.ResultType.accessDenied) {
                    window.location.href = __Global.accessDeniedUrl;
                } else if (resp.code == __Global.ResultType.unauthorized) {
                    window.top.location.href = __Global.loginUrl;
                } else if (resp.code == __Global.ResultType.serverError) {
                    this.thisApp.$Message.error("运行错误.请查看日志");
                    console.log(resp);
                } else {
                    if (callback) {
                        callback(resp);
                    }
                }
            },
            error(xhr, textStatus, errorThrown) {
                this.thisApp.$Message.error("访问出错");
                console.log("ajax post error [" + _url + "]");
                if (xhr) {
                    console.log(xhr.responseText);
                }
            }
        });
    };
}

/**
 * ----------------------------------------------------------------------------------------------
 * ------------------------ 扩展jQuery的Ajax方法-------------------------------------
 * ----------------------------------------------------------------------------------------------
 */
$.extend({

    // 重置父页面IFrame高度
    resetParentFrameHeight: function () {
        let offsetHeight = 0;
        if (document.documentElement && document.documentElement.offsetHeight) {
            offsetHeight = document.documentElement.offsetHeight;
        } else if (document.body) {
            offsetHeight = document.body.offsetHeight;
        }
        console.log(offsetHeight);

        $(window.parent.document).find("#contentFrame").css({
            "min-height": offsetHeight + "px"
        });

        return offsetHeight;
    },

    validateMobile: function (mobile) {
        let phoneReg = /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/;
        if (mobile && phoneReg.test(mobile)) {
            return true;
        }
        return false;
    }
    ,
    computeAge: function (birthday) {
        let age;
        if (!birthday) {
            return "";
        }
        let ymdNow = new Date().pattern("yyyy-MM-dd");
        let y = parseInt(ymdNow.split("-")[0]) - parseInt(birthday.split("-")[0]);
        let m = parseInt(ymdNow.split("-")[1]) - parseInt(birthday.split("-")[1]);
        let d = parseInt(ymdNow.split("-")[2]) - parseInt(birthday.split("-")[2]);
        age = y - 1;
        if (m >= 0 && d >= 0) {
            age++;
        }
        return age;
    }
    ,
    ajaxGet: function (url, data, callback) {
        let headers = {};
        $.ajax({
            url: url,
            type: "get",
            data: data,
            dataType: "json",
            headers: headers,
            xhrFields: {
                // 设置为true，避免跨域清空下漏传session
                withCredentials: true
            },
            timeout: 10000,
            success: function (rs) {
                if (rs.code == __Global.ResultType.accessDenied) {
                    window.location.href = __Global.accessDeniedUrl;
                } else if (rs.code == __Global.ResultType.unauthorized) {
                    window.top.location.href = __Global.loginUrl;
                } else if (rs.code == __Global.ResultType.serverError) {
                    app.$Message.error("运行错误.请查看日志");
                    console.log(rs);
                } else {
                    if (callback) {
                        callback(rs);
                    }

                }
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log("ajax get error");
                if (xhr) {
                    console.log(xhr.responseText);
                }

            }
        });
    }
    ,
    ajaxPost: function (url, data, callback, timeout) {
        let headers = {};
        $.ajax({
            url: url,
            type: "post",
            data: data,
            dataType: "json",
            headers: headers,
            xhrFields: {
                // 设置为true，避免跨域情况下漏传session
                withCredentials: true
            },
            timeout: timeout || 10000,
            success: function (rs) {
                if (rs.code == __Global.ResultType.accessDenied) {
                    window.location.href = __Global.accessDeniedUrl;
                } else if (rs.code == __Global.ResultType.unauthorized) {
                    window.top.location.href = __Global.loginUrl;
                } else if (rs.code == __Global.ResultType.serverError) {
                    app.$Message.error("运行错误.请查看日志");
                    console.log(rs);
                } else {
                    if (callback) {
                        callback(rs);
                    }

                }
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log("ajax post error");
                if (xhr) {
                    console.log(xhr.responseText);
                }
            }
        });
    }
    ,
    ajaxPostBody: function (url, data, callback) {
        let headers = {};
        $.ajax({
            url: url,
            type: "post",
            data: data,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            headers: headers,
            xhrFields: {
                // 设置为true，避免跨域清空下漏传session
                withCredentials: true
            },
            timeout: 10000,
            success: function (rs) {
                if (rs.code == __Global.ResultType.accessDenied) {
                    window.location.href = __Global.accessDeniedUrl;
                } else if (rs.code == __Global.ResultType.unauthorized) {
                    window.top.location.href = __Global.loginUrl;
                } else if (rs.code == __Global.ResultType.serverError) {
                    app.$Message.error("运行错误.请查看日志");
                    console.log(rs);
                } else {
                    if (callback) {
                        callback(rs);
                    }

                }
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log("ajax post error");
                if (xhr) {
                    console.log(xhr.responseText);
                }
            }
        });
    }
});

/**
 * ----------------------------------------------------------------------------------------------
 * ------------------------ 时间格式化
 * -------------------------------------------------
 * ----------------------------------------------------------------------------------------------
 */
Date.prototype.pattern = function (fmt) {
    if (!fmt) {
        //fmt = "yyyy-MM-dd HH:mm:ss";
        fmt = "yyyy-MM-dd";
    }
    let o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
        "H+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        S: this.getMilliseconds()
        // 毫秒
    };
    let week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (RegExp.$1.length > 1
                ? RegExp.$1.length > 2
                    ? "/u661f/u671f"
                    : "/u5468"
                : "") + week[this.getDay() + ""]
        );
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
            );
        }
    }
    return fmt;
};

